<template>
  <!-- 添加或修改销售信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="开票附件及开票信息填写" name="first">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开票单位" prop="customerId">
                <el-select v-model="form.customerId" placeholder="请选择开票单位" filterable @change="selectCustomer" clearable
                  style="width: 100%">
                  <el-option v-for="dict in dict.type.goods_customer" ref="myselectCustomer" :key="dict.value"
                    :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开票单位编码" prop="taxNo">
                <el-input style="width: 100%" v-model="form.taxNo" placeholder="请输入开票单位编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程名称" prop="gongchengName">
                <el-input style="width: 100%" v-model="form.gongchengName" placeholder="请输入开票单位编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开票金额" prop="amount">
                <el-input-number style="width: 100%" :precision="5" :min="0" v-model="form.amount"
                  placeholder="请输入销售额" />
              </el-form-item>
            </el-col>
<!--            <el-col :span="12">-->
<!--              <el-form-item label="申请时间" prop="applyTime">-->
<!--                <el-date-picker clearable v-model="form.invoiceApplyDate" type="datetime"-->
<!--                                value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                                placeholder="请选择申请时间">-->
<!--                </el-date-picker>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="24">
              <el-form-item label="开票明细" prop="files">
                <file-upload :limit="100" v-model="form.files" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <el-form :inline="true" :model="queryParams" label-width="98px" ref="queryForm" size="small" v-show="showSearch">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="搜索条件" name="first">
          <el-form-item label="框架编号" prop="projectCode">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入订单编号" v-model="queryParams.code" />
          </el-form-item>
          <el-form-item label="订单编号" prop="code">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入订单编号" v-model="queryParams.code" />
          </el-form-item>
          <el-form-item label="买方" prop="customName">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入买方" v-model="queryParams.customName" />
          </el-form-item>
          <el-form-item label="项目单位" prop="companyName">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入项目单位" v-model="queryParams.companyName" />
          </el-form-item>
          <el-form-item label="制单人" prop="createName">
            <el-input @keyup.enter.native="handleQuery" placeholder="请输入制单人" clearable  v-model="queryParams.createName" />
          </el-form-item>
          <el-form-item label="业务员" prop="salesmanName">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入业务员" v-model="queryParams.salesmanName" />
          </el-form-item>
          <el-form-item label="订单信息备注" prop="information">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入订单信息备注"
                      v-model="queryParams.information"/>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery" icon="el-icon-search" size="mini" type="primary">搜索</el-button>
            <el-button @click="resetQuery" icon="el-icon-refresh" size="mini">重置</el-button>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-table border v-loading="loading" ref="dragTable" :data="columns" row-key="id"
      @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column label="框架编号" align="center" prop="projectCode"/>
      <el-table-column label="订单编号" align="center" prop="code" show-overflow-tooltip />
      <el-table-column label="买方(开票单位)" align="center" prop="customName" />
      <el-table-column label="开票单位编码" align="center" prop="taxcode" />
      <el-table-column label="订单金额" align="center" prop="contractMoney" />
      <el-table-column label="剩余开票" align="center" prop="taxRemain" />
      <el-table-column label="开票金额" align="center" prop="taxAmount" width="210">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.taxAmount" size="mini" @change="taxAmountChange" :precision="2" :min="0" :max="scope.row.taxRemain"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="项目单位" align="center" prop="companyName" show-overflow-tooltip />
      <el-table-column label="下单日期" align="center" prop="orderDate"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="制单人" align="center" prop="createName" show-overflow-tooltip />
      <el-table-column label="业务员" align="center" prop="salesmanName" />
      <el-table-column label="地区" align="center" prop="area">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_area" :value="scope.row.area" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="information" show-overflow-tooltip/>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <goods-sale-list-select-for-invoice ref="GoodsSaleListSelectForInvoice"
      @ok="updateOrderList"></goods-sale-list-select-for-invoice>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitFormAll">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>


<script>
import {
  addAction,
  getAction,
  getById,
  deleteAction,
  updateAction, accAdd
} from '@/api/manage'
  import {
    updateGoodsSale
  } from '@/api/develop/goodsInvoiceBatch'
  import request from '@/utils/request'
  import GoodsSaleListSelectForInvoice from "../../goodsSale/GoodsSaleListSelectForInvoice";
import {parseTime} from "@/utils/common";

  export default {
    name: "GoodsInvoiceBatchHebing",
    components: {
      GoodsSaleListSelectForInvoice
    },
    dicts: ['company', 'goods_supplier', 'goods_customer', 'order_area'],
    data() {
      return {
        // 遮罩层
        loading: true,
        activeName: "first",
        // 弹出层标题
        title: "合并开票",
        // 是否显示弹出层
        open: false,
        // 显示搜索条件
        showSearch: true,
        // 表单参数
        form: {},
        columns: [],
        customerId: "",
        total: 0,
        ids: "",
        selectIds: "",
        selectIdsNew: [],
        selectRows: [],
        // 表单校验
        rules: {
          projectId: [{required: true,message: "请选择项目信息",trigger: "blur"}],
          customerId: [{required: true,message: "请选择客户信息",trigger: "blur"}],
          amount: [
            {required: true, message: "开票金额不能为空", trigger: "blur"},
            {validator: this.moneyValidator,trigger: 'blur'}
          ],
        },
        queryParams: {
          id: null,
          yearStr: null,
          pageNum: 1,
          pageSize: 20,
          name: null,
          code: null,
          master: null,
          customId: null,
          customName: null,
          companyName: null,
          contractDate: null,
          contractMoney: null,
          auditMoney: null,
          checkDate: null,
          checkState: null,
          fundCallback: null,
          information: null,
          createName: null,
          salesmanName: null,
          orderByColumn: "create_time",
          isAsc: "desc",
          params: {},
        },
        url: {
          listProject: '/projectBaseInfo/projectBaseInfo/listNotAllKp',
          proNames: '/projectBaseInfo/projectBaseInfo/prjNames',
          insertBatchAll: '/goodsInvoice/goodsInvoice/insertBatchAll',
        },
        orderInfo: {},
        proNameOptions: [],
      };
    },
    created() {},
    methods: {
      moneyValidator(rule, value, callback) {
        if (value === 0) {
          callback(new Error('开票金额不能为0'));
        } else {
          callback();
        }
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      showAddInvoiceHebing() {
        this.reset();
        this.selectIds = "";
        this.open = true;
        this.loading = false;
        this.form.invoiceApplyDate = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
        this.getList();
      },
      getList() {
        this.loading = true;
        getAction(this.url.listProject, this.queryParams).then(response => {
          this.columns = response.rows;
          for(let i = 0; i < this.columns.length; i++) {
            this.columns[i].taxAmount = this.columns[i].taxRemain;
          }
          this.total = response.total;
          this.loading = false;
        });
      },
      handleRemove(row) {
        let that = this;
        that.columns = that.columns.filter((item) => {
          return item.id != row.id
        });
        that.form.columns = that.columns;
        that.selectIdsNew = [];
        for (let i = 0; i < that.columns.length; i++) {
          let row = that.columns[i];
          that.selectIdsNew.push(row.id);
        }
        that.selectIds = that.selectIdsNew;
        that.$modal.msgSuccess("移除成功！");
      },
      updateOrderList(selectRows) {
        let that = this;
        for (let i = 0; i < selectRows.length; i++) {
          let row = selectRows[i];
          that.columns.push(row);
        }
        var totalPrice = 0;
        for (let i = 0; i < that.columns.length; i++) {
          let row = that.columns[i];
          that.selectIdsNew.push(row.id);
          totalPrice += row.goodsTotalPrice;
        }
        that.form.amount = totalPrice;
        that.selectIds = that.selectIdsNew;
      },
      handleAddList() {
        let that = this;
        that.$refs.GoodsSaleListSelectForInvoice.showSelectSaleDialog(that.selectIds, that.form.customerId);
      },
      selectCustomer(value) {
        let that = this;
        that.$nextTick(() => {
          let arr = that.$refs.myselectCustomer;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.customerName = arr[i].label;
            }
          }
        })
        this.queryParams.customId= value;
        this.getList();
      },
      selectSupplier(value) {
        let that = this;
        that.$nextTick(() => {
          let arr = that.$refs.myselectSsupplier;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.supplierName = arr[i].label;
            }
          }
        })
      },
      selectUser(value) {
        let that = this;
        that.$nextTick(() => {
          let arr = that.$refs.myselectUser;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.drawerName = arr[i].label;
            }
          }
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          goodsId: null,
          goodsName: null,
          goodsBrand: null,
          goodsUnitPrice: null,
          goodsCount: null,
          goodsTotalPrice: null,
          saleDate: null,
          supplierId: null,
          supplierName: null,
          customerId: null,
          customerName: null,
          invoiceCompany: "1",
          invoice: "0",
          invoiceId: null,
          invoiceNo: null,
          status: "wkp",
          fundCallback: "whx",
          receipt: null,
          saleId: null,
          saleName: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          deptId: this.$store.getters.deptId,
          deptName: this.$store.getters.deptName,
          invoiceApplyDate: null,
        };
        this.resetForm("form");
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
        this.selectRows = selection;
        this.sumTotalMoney();
      },

      taxAmountChange(){
        this.sumTotalMoney();
      },

      sumTotalMoney() {
        let totalMoney = 0;
          for (let i = 0; i < this.selectRows.length; i++) {
              totalMoney  = accAdd(totalMoney, this.selectRows[i].taxAmount)
          }
        this.form.amount = totalMoney;
      },
      /** 提交按钮 */
      submitFormAll() {
        let that = this;
        that.$refs["form"].validate(valid => {
          if (valid) {
            const forms = that.form;
            const proForm = Object.assign({}, forms);
            proForm.columns = that.selectRows;
            addAction(that.url.insertBatchAll, proForm).then(response => {
              that.$modal.msgSuccess("申请完成！");
              that.open = false;
              that.$emit('ok');
            });
          }
        });
      },
    }
  };
</script>
